package com.example.admin.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.example.admin.constants.AdminConstant;
import com.example.admin.feign.ArticleFeign;
import com.example.admin.feign.WemediaFeign;
import com.example.admin.mapper.ChannelMapper;
import com.example.admin.mapper.SensitiveMapper;
import com.example.admin.service.WmNewsCheckService;
import com.usian.common.aliyun.GreenImageScan;
import com.usian.common.aliyun.GreenTextScan;
import com.usian.common.fastdfs.FastDFSClient;
import com.usian.model.admin.pojos.AdChannel;
import com.usian.model.admin.pojos.AdSensitive;
import com.usian.model.article.dtos.ApArticleDto;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.media.pojos.WmNews;
import com.usian.utils.common.SensitiveWordUtil;
import com.usian.utils.common.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;


@Service
public class WmNewsCheckServiceImpl implements WmNewsCheckService {
    @Autowired
    private WemediaFeign wemediaFeign;
    //@Autowired
    //private GreenImageScan greenImageScan;
    //@Autowired
    //private GreenTextScan greenTextScan;
    @Autowired
    private SensitiveMapper sensitiveMapper;
    //@Autowired
    //FastDFSClient fastDFSClient;
    @Autowired
    private ChannelMapper channelMapper;
    @Autowired
    private ArticleFeign articleFeign;
    
    
    /**
     * 主要业务流程   判断
     *
     * @param id id
     */
    @Override
    public ResponseResult checkWmNews(Integer id) {
        //参数校验
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        WmNews wmNews = wemediaFeign.getWmNewsById(id);
        //调用自媒体微服务返回文章信息
        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        Integer status = wmNews.getStatus();
        if (status == 8) {//审核通过  待发布
            if (wmNews.getPublishTime().getTime() <= System.currentTimeMillis()) {
                //发布  保存数据article  调用article提供的接口
                AdChannel adChannel = channelMapper.selectById(wmNews.getChannelId());
                ApArticleDto apArticleDto = new ApArticleDto();
    
               
                
                
                articleFeign.addArticle(apArticleDto);
            }
        }
        if (status == 1) {//待审核
            Map<String, Object> map = getNewsTextAndImage(wmNews);
            //文本检测
            String content = (String) map.get("text");
            String res = checkText(content);
            if (res.equals("block")) {
                wemediaFeign.updateWmNewsById(new WmNews(id, 2, "检测失败"));
            }
            if (res.equals("review")) {
                wemediaFeign.updateWmNewsById(new WmNews(id, 3, "需要人工审核"));
            }
            //图片检测
            List<String> imgList = (List<String>) map.get("images");
            String imgRes = checkImg(imgList);
            if (imgRes.equals(AdminConstant.CHECK_RESULT_BLOCK)){
                wemediaFeign.updateWmNewsById(new WmNews(id,2,"检测失败"));
            }
            if (imgRes.equals(AdminConstant.CHECK_RESULT_REVIEW)){
                wemediaFeign.updateWmNewsById(new WmNews(id, 3, "需要人工审核"));
            }
            wemediaFeign.updateWmNewsById(new WmNews(id, 8, null));
    
        }
        
        
        return null;
    }
    
    
    /**
     * 图片检测
     *
     * @param imgList imgList
     */
    public String checkImg(List<String> imgList) {
        List<byte[]> list = new ArrayList<>();
        try {
            for (String img : imgList) {
                HashMap<String, String> map = StringUtils.subStringPath(img);
                //byte[] imagesByte = fastDFSClient.download(map.get("group"), map.get("path"));
                //list.add(imagesByte);
            }
            //return greenImageScan.imageScan(list);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AdminConstant.CHECK_RESULT_BLOCK;
    }
        
        /**
         * 检查文本
         *
         * @param content 内容
         */
        private String checkText (String content){
            //敏感词的校验
            List<AdSensitive> sensitiveList = sensitiveMapper.selectList(null);
            List<String> wordList = sensitiveList.stream().map(AdSensitive::getSensitives).collect(Collectors.toList());
            SensitiveWordUtil.initMap(wordList);
            Map<String, Integer> map = SensitiveWordUtil.matchWords(content);
            if (map.size() > 0) {
                return "block";
            }
            
            try {
                //return greenTextScan.greenTextScan(content);
            } catch (Exception e) {
                e.printStackTrace();
            }
            
            return "";
        }
        
        private Map<String, Object> getNewsTextAndImage (WmNews wmNews){
            String content = wmNews.getContent();
            //接收循环出来的文字和图片
            StringBuilder stringBuilder = new StringBuilder();//因为要重复拼接字符串，而String长度是不可变的，只会生成新的String对象
            List<String> imgList = new ArrayList<>();
            
            if (!content.equals("")) {
                List<Map> maps = JSONArray.parseArray(content, Map.class);
                for (Map map : maps) {
                    if (map.get("type").equals("text")) {
                        stringBuilder.append(map.get("value"));
                    }
                    if (map.get("type").equals("image")) {
                        String value = (String) map.get("value");
                        String subImg = StringUtils.substringPath(value);
                        imgList.add(subImg);
                    }
                }
            }
            String images = wmNews.getImages();
            if (!images.equals("")) {
                //根据  ,  截取
                String[] split = images.split(",");
                //把两个list合成一个
                imgList.addAll(Arrays.asList(split));
            }
            
            HashMap<String, Object> map = new HashMap<>();
            map.put("text", stringBuilder.toString());
            map.put("images", imgList);
            return map;
        }
    }
